// src/MqttComponent.js  13.56.227.196:3005"
import React, { useState, useEffect } from 'react';
import mqtt from 'mqtt';

const MqttComponent = () => {
    const [client, setClient] = useState(null);
    const [isConnected, setIsConnected] = useState(false);
    const [messages, setMessages] = useState([]);

    useEffect(() => {
        const mqttClient = mqtt.connect('mqtt://13.56.227.196:3005', {
            clean: true,
            clientId: "12345645656",
            username: "server",
            password: "server",
            connectTimeout: 4000,
            rejectUnauthorized: false,
            reconnectPeriod: 1000,

        });

        setClient(mqttClient);

        mqttClient.on('connect', () => {
            setIsConnected(true);
            console.log('Connected to MQTT broker');
            mqttClient.subscribe('test/topic', (err) => {
                if (err) {
                    console.error('Subscribe error:', err);
                } else {
                    console.log('Subscribed to test/topic');
                }
            });
        });

        mqttClient.on('error', (error) => {
            console.error('Connection error: ', error);
        });

        mqttClient.on('message', (topic, message) => {
            console.log('Received message:', topic, message.toString());
            setMessages((prevMessages) => [
                ...prevMessages,
                { topic, message: message.toString() },
            ]);
        });

        return () => {
            if (mqttClient) {
                mqttClient.end();
            }
        };
    }, []);

    const handlePublish = () => {
        if (client) {
            client.publish('test/topic', 'Hello MQTT');
        }
    };

    return (
        <div>
            <h1>MQTT Demo</h1>
            <p>Connection Status: {isConnected ? 'Connected' : 'Disconnected'}</p>
            <button onClick={handlePublish} disabled={!isConnected}>
                Publish Message
            </button>
            <h2>Messages</h2>
            <ul>
                {messages.map((msg, index) => (
                    <li key={index}>
                        {msg.topic}: {msg.message}
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default MqttComponent;
